package assignments.sagarjoshi.springtms;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;


public class Activity_TraineeHome extends Activity {

    private DateFormat df, dd;
    private Calendar cal;
    private String date;
    private TextView txt_date;
    private String data[] = new String[3];
    private boolean flag;
    private String trainee_id,cur_status;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_traineehome);

        SharedPreferences sp = getSharedPreferences("session", this.MODE_PRIVATE);
        String email_id = sp.getString("email_id", "");

        if (email_id.equals("")) {
            Intent go_login = new Intent(this, LoginScreen.class);
            startActivity(go_login);
        }

        getTraineeID(email_id);   //// call method to obtain Trainee ID

        txt_date = (TextView) findViewById(R.id.txt_date);
        df = new SimpleDateFormat("dd/MM/yyyy");
        String date = df.format(Calendar.getInstance().getTime());
        txt_date.setGravity(Gravity.CENTER);
        txt_date.setText(date);

        final Button btn_frwd = (Button) findViewById(R.id.move_frwd);
        final Button btn_bck = (Button) findViewById(R.id.move_back);
        final Button btn_cnfrm = (Button) findViewById(R.id.btn_confirm);
        final Button btn_reject = (Button) findViewById(R.id.btn_reject);


        update_field();   //// called for the first time to update fields according to current date


        btn_frwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dd = new SimpleDateFormat("dd");
                String curr_date = dd.format(Calendar.getInstance().getTime());
                data = txt_date.getText().toString().split("/");
                int diff = (Integer.parseInt(data[0]) - Integer.parseInt(curr_date)) + 1;
                if (diff <= 5) {
                    cal = Calendar.getInstance();
                    cal.add(Calendar.DATE, diff);

                    String date = df.format(cal.getTime());
                    txt_date.setGravity(Gravity.CENTER);
                    txt_date.setText(date);
                }

                update_field();

                SQLiteDatabase mydb = new MyDatabaseHelper(getApplicationContext()).getReadableDatabase();
                String tablename=MyDatabaseHelper.DATABASE_TABLE_TRAINEE_COURSE;
                String projection[]=new String[]{MyDatabaseHelper.KEY_STATUS};
                String where=MyDatabaseHelper.KEY_ALLOCATED_DATE+" = ? AND "+MyDatabaseHelper.KEY_TRAINEE_ID+" = ?";
                String where_args[]= new String[]{data[2]+"-"+data[1]+"-"+data[0],trainee_id};
                Log.i("date : ",data[2]+"-"+data[1]+"-"+data[0]);
                Cursor cur_status = mydb.query(tablename,projection,where,where_args,null,null,null);


                if(cur_status.getCount() > 0) {

                    cur_status.moveToNext();
                    String status = cur_status.getString(0);

                    if (diff >= 0) {
                        btn_cnfrm.setEnabled(true);
                        btn_reject.setEnabled(true);

                        if (status.equals("confirmed")) {
                            btn_cnfrm.setText("confirmed");
                            btn_reject.setText("reject");
                            btn_cnfrm.setEnabled(false);
                            btn_reject.setEnabled(true);
                        } else if (status.equals("rejected")) {
                            btn_reject.setText("rejected");
                            btn_cnfrm.setText("confirm");
                            btn_reject.setEnabled(false);
                            btn_cnfrm.setEnabled(true);
                        } else {
                            btn_cnfrm.setText("confirm");
                            btn_reject.setText("reject");
                        }

                    } else {
                        btn_cnfrm.setEnabled(false);
                        btn_reject.setEnabled(false);

                        if (status.equals("confirmed")) {
                            btn_cnfrm.setText("confirmed");
                            btn_reject.setText("reject");

                        } else if (status.equals("rejected")) {
                            btn_reject.setText("rejected");
                            btn_cnfrm.setText("confirm");

                        } else {
                            btn_cnfrm.setText("confirm");
                            btn_reject.setText("reject");
                        }
                    }
                }
                else
                {
                    btn_cnfrm.setText("confirm");
                    btn_reject.setText("reject");
                    btn_cnfrm.setEnabled(false);
                    btn_reject.setEnabled(false);
                }

            mydb.close();
            }
        });

        btn_bck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dd = new SimpleDateFormat("dd");
                String curr_date = dd.format(Calendar.getInstance().getTime());
                data = txt_date.getText().toString().split("/");
                int diff = (Integer.parseInt(data[0]) - Integer.parseInt(curr_date)) - 1;
                if (diff >= -5) {
                    cal = Calendar.getInstance();
                    cal.add(Calendar.DATE, diff);

                    String date = df.format(cal.getTime());
                    txt_date.setGravity(Gravity.CENTER);
                    txt_date.setText(date);
                }

                update_field();

                    SQLiteDatabase mydb = new MyDatabaseHelper(getApplicationContext()).getReadableDatabase();
                    String tablename = MyDatabaseHelper.DATABASE_TABLE_TRAINEE_COURSE;
                    String projection[] = new String[]{MyDatabaseHelper.KEY_STATUS};
                    String where = MyDatabaseHelper.KEY_ALLOCATED_DATE + " = ? AND " + MyDatabaseHelper.KEY_TRAINEE_ID + " = ?";
                    String where_args[] = new String[]{data[2] +"-"+ data[1] +"-"+ data[0], trainee_id};

                    Cursor cur_status = mydb.query(tablename, projection, where, where_args, null, null, null);

                if(cur_status.getCount() > 0) {
                    cur_status.moveToNext();
                    String status = cur_status.getString(0);

                    if (diff >= 0) {
                        btn_cnfrm.setEnabled(true);
                        btn_reject.setEnabled(true);

                        if (status.equals("confirmed")) {
                            btn_cnfrm.setText("confirmed");
                            btn_reject.setText("reject");
                            btn_cnfrm.setEnabled(false);
                            btn_reject.setEnabled(true);
                        } else if (status.equals("rejected")) {
                            btn_reject.setText("rejected");
                            btn_cnfrm.setText("confirm");
                            btn_reject.setEnabled(false);
                            btn_cnfrm.setEnabled(true);
                        } else {
                            btn_cnfrm.setText("confirm");
                            btn_reject.setText("reject");
                        }

                    } else {
                        btn_cnfrm.setEnabled(false);
                        btn_reject.setEnabled(false);

                        if (status.equals("confirmed")) {
                            btn_cnfrm.setText("confirmed");
                            btn_reject.setText("reject");

                        } else if (status.equals("rejected")) {
                            btn_reject.setText("rejected");
                            btn_cnfrm.setText("confirm");

                        } else {
                            btn_cnfrm.setText("confirm");
                            btn_reject.setText("reject");
                        }
                    }
                }
                else
                {
                    btn_cnfrm.setText("confirm");
                    btn_reject.setText("reject");
                    btn_cnfrm.setEnabled(false);
                    btn_reject.setEnabled(false);
                }

            mydb.close();
            }
        });

        btn_reject.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
                final View confirmDialog = inflater.inflate(R.layout.reject_dialog_layout, null);
                final AlertDialog dialog = new AlertDialog.Builder(Activity_TraineeHome.this).create();
                dialog.setView(confirmDialog);
                dialog.setTitle("CONFIRMATION !!! ");

                confirmDialog.findViewById(R.id.btn_yes).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        EditText edit = (EditText) confirmDialog.findViewById(R.id.reason_edit_Text);
                        if (edit.getText().toString().isEmpty()) {
                            Toast.makeText(getApplicationContext(), "Please Enter a Reason", Toast.LENGTH_LONG).show();
                        } else {

                            SQLiteDatabase mydb = new MyDatabaseHelper(getApplicationContext()).getWritableDatabase();
                            String tablename = MyDatabaseHelper.DATABASE_TABLE_TRAINEE_COURSE;
                            String where = "allocated_date = ? and trainee_id = ?";

                            data = txt_date.getText().toString().split("/");
                            String txtview_date = data[2] + "-" + data[1] + "-" + data[0];

                            String where_args[] = new String[]{txtview_date, trainee_id};

                            Log.i(txtview_date, trainee_id);

                            ContentValues contentValues = new ContentValues();
                            contentValues.put(MyDatabaseHelper.KEY_STATUS, "rejected");
                            contentValues.put(MyDatabaseHelper.KEY_COMMENTS, edit.getText().toString());

                            mydb.update(tablename, contentValues, where, where_args);

                            btn_reject.setText("rejected");
                            btn_reject.setEnabled(false);
                            btn_cnfrm.setText("confirm");
                            btn_cnfrm.setEnabled(true);

                            dialog.dismiss();
                            mydb.close();
                        }
                    }
                });

                confirmDialog.findViewById(R.id.btn_no).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                dialog.show();

            }
        });


        btn_cnfrm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
                final View confirmDialog = inflater.inflate(R.layout.confirm_dialog_layout, null);
                final AlertDialog dialog = new AlertDialog.Builder(Activity_TraineeHome.this).create();
                dialog.setView(confirmDialog);
                dialog.setTitle("CONFIRMATION !!! ");

                confirmDialog.findViewById(R.id.btn_yes).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                            SQLiteDatabase mydb = new MyDatabaseHelper(getApplicationContext()).getWritableDatabase();
                            String tablename = MyDatabaseHelper.DATABASE_TABLE_TRAINEE_COURSE;
                            String where = "allocated_date = ? and trainee_id = ?";

                            data = txt_date.getText().toString().split("/");
                            String txtview_date = data[2] + "-" + data[1] + "-" + data[0];

                            String where_args[] = new String[]{txtview_date, trainee_id};

                            Log.i(txtview_date, trainee_id);

                            ContentValues contentValues = new ContentValues();
                            contentValues.put(MyDatabaseHelper.KEY_STATUS, "confirmed");
                        contentValues.put(MyDatabaseHelper.KEY_COMMENTS,"");

                            mydb.update(tablename, contentValues, where, where_args);

                            btn_cnfrm.setText("confirmed");
                            btn_cnfrm.setEnabled(false);
                            btn_reject.setText("reject");
                            btn_reject.setEnabled(true);

                            dialog.dismiss();
                            mydb.close();

                    }
                });

                confirmDialog.findViewById(R.id.btn_no).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                dialog.show();
            }
        });

    }


    private void getTraineeID(String email_id) {
        SQLiteDatabase mydb = new MyDatabaseHelper(this).getReadableDatabase();
        String tablename = MyDatabaseHelper.DATABASE_TABLE_TRAINEE;
        String projection[] = new String[]{tablename + "._id"};
        String selection = MyDatabaseHelper.KEY_EMAIL_ID + " = ?";
        String args[] = new String[]{email_id};

        Cursor cur_trainee_id = mydb.query(tablename, projection, selection, args, null, null, null);

        cur_trainee_id.moveToNext();

        trainee_id = cur_trainee_id.getInt(0) + "";

        mydb.close();
    }


    private void update_field() {

        TextView sessiontopic_data = (TextView) findViewById(R.id.session_topic_data);
        TextView Trainername_data = (TextView) findViewById(R.id.Trainer_name_data);
        TextView place_data = (TextView) findViewById(R.id.place_data);
        TextView description_data = (TextView) findViewById(R.id.description_data);


            data = txt_date.getText().toString().split("/");
            String txtview_date = data[2] + "-" + data[1] + "-" + data[0];

            SQLiteDatabase mydb = new MyDatabaseHelper(this).getReadableDatabase();
            String tablename = MyDatabaseHelper.DATABASE_TABLE_TRAINEE_COURSE;
            String projection[] = new String[]{MyDatabaseHelper.KEY_COURSE_ID};
            String selection = MyDatabaseHelper.KEY_ALLOCATED_DATE + "= ? AND " + MyDatabaseHelper.KEY_TRAINEE_ID + " = ?";
            String args[] = new String[]{txtview_date, trainee_id};

            Cursor outer_cursor = mydb.query(tablename, projection, selection, args, null, null, null);

            if (outer_cursor.getCount() > 0) {
                flag = true;
                outer_cursor.moveToNext();

                tablename = MyDatabaseHelper.DATABASE_TABLE_COURSE;
                String inner_projection[] = new String[]{MyDatabaseHelper.KEY_COURSE_NAME, MyDatabaseHelper.KEY_COURSE_MENTOR_NAME, MyDatabaseHelper.KEY_COURSE_PLACE, MyDatabaseHelper.KEY_COURSE_DESCRIPTION};
                String inner_selection = tablename + "._id = ?";
                String inner_args[] = {outer_cursor.getInt(0) + ""};

                Cursor inner_cursor = mydb.query(tablename, inner_projection, inner_selection, inner_args, null, null, null);

                inner_cursor.moveToNext();

                sessiontopic_data.setText(inner_cursor.getString(0));
                Trainername_data.setText(inner_cursor.getString(1));
                place_data.setText(inner_cursor.getString(2));
                description_data.setText(inner_cursor.getString(3));


            } else {
                flag = false;
                sessiontopic_data.setText("");
                Trainername_data.setText("");
                place_data.setText("");
                description_data.setText("");
            }

            mydb.close();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_admin_home, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        //noinspection SimplifiableIfStatement

        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_logout) {
            startActivity(new Intent(this, LoginScreen.class));
            this.finish();

        }

        return super.onOptionsItemSelected(item);
    }
}